package com.dycong.common.IO.netty.first;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * Created by dycong on 2017/3/13.
 */
//TODO 继承时指定泛型类型ByteBuf后，覆盖的方法才能在参数签名指定类型，否则，不指定的话可选Object
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

    static int count = 0;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        this.channel = ctx;
        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!"+(++count), //2服务器的连接被建立后调用,当被通知该 channel 是活动的时候就发送信息
                CharsetUtil.UTF_8));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx,
                               Object msg) throws Exception {
        System.out.println("ClientReader received: " + msg.toString());    //3数据从服务器接收后到调用,处理返回的信息
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
                                Throwable cause) {                    //4
        cause.printStackTrace();
        ctx.close();
    }

    ChannelHandlerContext channel;

    public boolean sendMsg(String msg) {
        System.out.println("客户端发送消息：" + msg);
        byte[] req = msg.getBytes();
        ByteBuf m = Unpooled.compositeBuffer(req.length);
        m.writeBytes(req);
        channel.writeAndFlush(m);
        return msg.equals("q") ? false : true;
    }
}
